import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions } from "react-native";
import { style } from '../../../../../theme/style';
import { GoodsItem } from './GoodsItem';

const ScreenWidth = Dimensions.get('window').width;
const scale = ScreenWidth / 375;

const defaultGoods = { goodsName: '', priceType: '1', symbol: true };

/* 
	notAdd:控制商品add , 控制商品字段是否能编辑
*/

export class GoodsModuleCpt extends Component {

	constructor(props) {
		super(props);
		let { data } = props || {};
		let { editeData } = data || {};
		if (!editeData || !editeData.length) {
			editeData = null;
		}
		let initData = editeData || [{ ...defaultGoods }];
		this.state = {
			goodsData: initData
		}

	}

	async componentWillReceiveProps(props) {
		let { data } = props || {};
		let { editeData } = data || {};
		if (!editeData || !editeData.length) {
			editeData = null;
		}
		let initData = editeData || [{ ...defaultGoods }];
		this.setState({
			goodsData: initData
		})
	}


	//新增商品
	_addGoodsFn = () => {
		let { goodsData } = this.state || {};
		let lsDefaultGoods = Object.assign({}, defaultGoods);
		lsDefaultGoods.priceType = goodsData[0].priceType;
		goodsData.push({ ...lsDefaultGoods });
		this.setState({
			goodsData
		}, () => {
			this._GoodsCallback(goodsData)
		})
	}

	//删除商品
	_removeGoodsFn = (index) => {
		let { goodsData } = this.state || {};
		goodsData.splice(index, 1);
		this.setState({
			goodsData
		}, () => {
			this._GoodsCallback(goodsData)
		})
	}

	//修改
	_changeGoodsFn = (goodsData) => {
		this.setState({
			goodsData
		}, () => {
			this._GoodsCallback(goodsData)
		})
	}

	//回调
	_GoodsCallback = () => {
		let { goodsData } = this.state;
		let { goodsCallback } = this.props || {};
		goodsCallback && goodsCallback(goodsData);
	}

	render() {
		let { data, dictionaryData, notAdd } = this.props || {};
		let { bizModel, salesType, salesRuleId } = data || {};
		let { goodsData } = this.state;
		return (
			<View>
				{
					notAdd ? null : <View style={styles.goodsAddBox}>
						<Text style={styles.goodsAdd} onPress={this._addGoodsFn}>【新增商品】</Text>
					</View>
				}
				{
					goodsData && goodsData.map((item, index) => {
						return <GoodsItem key={index}
							dictionaryData={dictionaryData}
							data={{ bizModel, goodsIndex: index, goodsData, salesType, salesRuleId }}
							event={{ removeGoods: this._removeGoodsFn, changeGoods: this._changeGoodsFn }}
							notAdd={notAdd || false}
						/>
					})
				}
			</View>
		)
	}
}

const styles = StyleSheet.create({
	goodsAddBox: {
		flex: 1,
		flexDirection: 'row',
		justifyContent: 'flex-end'
	},
	goodsAdd: {
		color: style.color.themeColor,
		paddingVertical: 10 * scale,
		width: 80 * scale,
		fontSize: 13 * scale
	}
})